﻿@inject DbService DbService
@inject GlobalNotificationService GlobalNotificationService

<div class="relative p-6 sm:p-8 bg-white dark:bg-gray-700 rounded-lg sm:shadow-xl max-w-md w-full mx-auto">
    <div class="text-center">
        <div class="space-y-4">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white">Vault merge required</h2>
            <p class="text-sm text-gray-500 dark:text-gray-400">
                A merge is required because another client has made changes to the vault since you last synced.
            </p>

            <div>
                @if (ErrorMessage.Length > 0)
                {
                    <AlertMessageError Message="@ErrorMessage" />
                }

                @if (IsMerging)
                {
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                        Please wait while the merge is performed. This process may take a moment.
                    </p>
                    <BoldLoadingIndicator />
                }
                else
                {
                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                        Please click the button below to begin the merge process.
                    </p>
                    <button @onclick="MergeDatabase" type="button" class="px-4 py-2 text-white bg-primary-600 rounded-lg hover:bg-primary-700 focus:ring-4 focus:ring-primary-300 dark:bg-primary-500 dark:hover:bg-primary-600 dark:focus:ring-primary-800">
                        Start vault merge
                    </button>
                }
            </div>
        </div>
    </div>
</div>

@code {
    private bool IsMerging { get; set; } = false;
    private string ErrorMessage { get; set; } = string.Empty;

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }

    /// <summary>
    /// Merges the databases.
    /// </summary>
    private async Task MergeDatabase()
    {
        // Show loading indicator
        IsMerging = true;
        ErrorMessage = String.Empty;
        StateHasChanged();

        try
        {
            await DbService.MergeDatabasesAsync();
        }
        catch (Exception ex)
        {
            ErrorMessage = ex.Message;
        }

        // Reset local state
        IsMerging = false;
        StateHasChanged();
    }
}
